//
//  WWStatusDAL.swift
//  SinWEiBo
//
//  Created by 胡良志 on 2018/5/23.
//  Copyright © 2018年 HuLiangZhi. All rights reserved.
//

import UIKit

class WWStatusDAL: NSObject {
    
    //加载数据
    class func loadHomeData (sinceId:Int64,maxId:Int64,finished:@escaping ([[String : Any]]?) -> () ){
        //查找数据库有无缓存数据,有就返回,没有从网络加载
        guard let res = checkoutStatus(sinceId: sinceId, maxId: maxId) else {return}
        //count > 0 说明有缓存
        if res.count > 0 {
            finished(res)
            return
        }
        //没有缓存
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let paramenters = ["access_token":WWUserAccountViewModel.shared.userAccount?.access_token,
                                   "max_id" : "\(maxId)",
                                   "since_id" : "\(sinceId)"]
        WWNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: paramenters) { (responseObjceve, error) in
            if (error != nil) {
                finished(nil)
                return
                
            }
            //          转换成字典类型
            let dict = responseObjceve as! [String : Any]
            //取出需要的数据并尝试转换成字典类型的数组
            guard let array = dict["statuses"] as? [[String : Any]] else { return }
            
            finished(array)
            //缓存到本地
            cacheStatus(array: array)
        }
        
    }
    

    //存储数据
       class func cacheStatus(array : [[String:Any]] ){
        
        guard let userId = WWUserAccountViewModel.shared.userAccount?.uid else {
            print("用户没有登陆"); return}
        // OR REPLACE 如果数据相同就覆盖掉
        let sql = "INSERT OR REPLACE INTO T_Status (statusId,status,userId) VALUES (?,?,?)"
        
        WWSQLiteTools.shared.queue.inTransaction { (db, rollback) in
            for item in array {
                let statusId = item["id"]
                //数据库中能够存储的数据不能够是Foundation 需要将字典数据转换二进制数据存储到数据库中
                //如果是字典数据 在读取的时候会有问题
                let jsonData = try!JSONSerialization.data(withJSONObject: item, options: [])
                let result = db.executeUpdate(sql, withArgumentsIn: [statusId ?? "",jsonData,userId])
                if !result{
                    //不成功就执行回滚
                    rollback.pointee = true
                    return
                }
            }
        }
    }
    
    //查找数据(分页)
    class func checkoutStatus(sinceId:Int64,maxId:Int64) -> [[String : Any]]?{
        
        guard let userId = WWUserAccountViewModel.shared.userAccount?.uid else {return nil}
         //会将数据库中所有的缓存数据都查找到
        var sql = "SELECT status FROM T_Status WHERE userId = \(userId) "
        //拼接sql
        //如果sinceId > 0 标识需要查找新数据
        if sinceId > 0 {
            //向上查找
            sql += "AND statusId > \(sinceId) "
        }
        if maxId > 0 {
            //向下查找
            sql += "AND statusId < \(maxId) "
        }
        //排序 降序
        sql += "ORDER BY statusId DESC "
        //限制条数
        sql += "LIMIT 20"
//        print(sql)
        var array = [[String : Any]]()
        
        WWSQLiteTools.shared.queue.inDatabase { (db) in
        
           let res = try! db.executeQuery(sql, values: nil)
            //逐条获取数据
            while res.next(){
                let jsonData = res.data(forColumn: "status")
                let dict = try!JSONSerialization.jsonObject(with: jsonData!, options: [])
                array.append(dict as! [String : Any])
            }
        }
//        print("---\(array.count)")
        return array
    }
    
    
    
    
    
    
}
